package com.blueocean_health.care.management.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.blueocean_health.care.management.common.base.string.StringUtils;
import com.blueocean_health.care.management.mapper.RoleMapper;
import com.blueocean_health.care.management.service.PowerService;

/**
 * 权限清单Service
 * 
 * @author 陆学
 * @date 2018年3月29日 上午10:33:34
 * @version 版本号：1.0
 */
@Service
public class PowerServiceImpl implements PowerService {
	@Autowired
	private RoleMapper roleMapper;


	/**
	 * 获得在某组织/项目下用户的权限，只包含power_code
	 * 
	 * @param userId 用户ID
	 * @param teamId 组织ID
	 */
	@Override
	public List<String> getPermissionsNew(String userId, String teamId) {
		Map<String, String> paramsMap = new HashMap<>();
		paramsMap.put("userId", userId);
		paramsMap.put("teamId", teamId);
		if (StringUtils.isEmpty(teamId)) {
			return null;
		}
		// 1.权限列表取并集
		List<String> permissionList = roleMapper.findAllUserPermissionByUserIdAndTeamId(paramsMap);
		if (null != permissionList && permissionList.size() > 0) {
			permissionList = permissionList.stream().filter(p -> !StringUtils.isEmpty(p)).collect(Collectors.toList());
		}
		if (null == permissionList || permissionList.size() <= 0) {
			return null;
		}
		// 2.模块的所属权限
		List<String> teamPowerList = roleMapper.findTeamPowersByTeamId(paramsMap);
		if (null != teamPowerList && teamPowerList.size() > 0) {
			teamPowerList = teamPowerList.stream().filter(t -> !StringUtils.isEmpty(t)).collect(Collectors.toList());
		}
		if (null == teamPowerList || teamPowerList.size() <= 0) {
			return null;
		}

		// 3.组织可用模块和权限列表取交集
		List<String> results = new ArrayList<>();
		for (String t : teamPowerList) {
			if (!StringUtils.isEmpty(t) && permissionList.contains(t)) {
				results.add(t);
			}
		}
		return results;
	}


}
